package com.fufan.mtsaas.modules.sysmgr.tsysparam.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fufan.mtsaas.config.RedissonCommand;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.modules.base.log.bo.request.LogSaveRequest;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.common.bo.request.DeleteRequest;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.bo.CirculationStatusBo;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.bo.request.SysParamQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.bo.request.SysParamSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.bo.response.FlowStatusResponse;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.dao.TSysParamDao;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.model.TSysParam;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.service.TSysParamSvc;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.ParamUtil;
import com.github.pagehelper.ISelect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RLock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Liby
 * @since 20125-03-01
 */
@Service("TSysParamSvcImpl")
@Slf4j
@Primary
public class TSysParamSvcImpl extends ServiceImpl<TSysParamDao, TSysParam> implements TSysParamSvc {
    @Autowired
    private TSysParamDao entitymDao;

    @Autowired
    private RedissonCommand redissonCommand;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TSysLogSvc tSysLogSvc;

    @Value("${COMPANY_ID}")
    private String COMPANY_ID;

    @Autowired
    private ParamUtil paramUtil;


    /**
     * 查询
     *
     * @param map
     * @return Result.class
     */
    @Override
    public Result doQueryPage(SysParamQueryRequest map) {
        RequestPojo requestPojo = ParamUtil.doChange();
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("TSysParamSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();

        String Name = map.getParamName();

        if (Objects.nonNull(map.getId()) && map.getId() != 0) {
            mapData.put("ID", String.valueOf(map.getId()));
        }
        mapData.put("paramName", Name);

        List<TSysParam> entitys;

        //分页处理 -- 20192021 Liby
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectList(page, mapData);
            }
        });

        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        entitys = entitymDao.selectList(page, mapData);
        log.debug("TSysParamSvcImpl.doQueryPage entitys: {}", entitys);

        page.setTotal((int) total);
        page.setRecords(entitys);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 获取流程状态
     */
    @Override
    public Result doQueryFlowStatus(SysParamQueryRequest map) {
        log.debug("TSysParamSvcImpl.doQueryFlowStatus parameter: {}", map);
        Result result = new Result();
        Page page = new Page();
        FlowStatusResponse response = new FlowStatusResponse();

        if (Objects.isNull(map.getParamName())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        String paramName = paramUtil.getTSysParam(map.getParamName() + "_XJS_CIRCULATION_STATUS");
        List<CirculationStatusBo> circulationStatusBoList = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            circulationStatusBoList = mapper.readValue(paramName, new TypeReference<List<CirculationStatusBo>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
            result.setResStatus(ResStatus.STATUS_FAILED);
            result.setResMsg(ResStatus.STATUS_FAILED_MSG + ":" + e.getLocalizedMessage());
            return result;
        }

        response.setFlowStatus(circulationStatusBoList);
        page.setTotal(1);
        page.setRecords(Arrays.asList(response));
        result.setResData(page);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        return result;
    }

    /**
     * 新增
     *
     * @param map
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doSave(SysParamSaveRequest map, RequestPojo requestPojo) {
        Integer TSysParamId = map.getId();
        log.debug("TSysParamSvcImpl.doSave parameter: {}", map);
        Result result = new Result();

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        mapData.put("paramName", map.getParamName());

        List<TSysParam> entitys = entitymDao.selectList(page, mapData);
        if (CollectionUtils.isNotEmpty(entitys) && entitys.size() > 0) {
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("该参数名称" + map.getParamName() + ResStatus.STATUS_EXISTENCE_MSG);
            return result;
        }

        TSysParam entitym = new TSysParam();
        BeanUtils.copyProperties(map, entitym);

        entitym.setId(-1L);
        entitym.setCreateBy(requestPojo.getUserName());
        entitym.setCreateTime(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        entitym.setUpdateBy(requestPojo.getUserName());
        entitym.setUpdateTime(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));

        try {
            RLock rLock = redissonCommand.getFairLock(String.valueOf(entitym.getId()));
            if (rLock.tryLock()) {
                try {
                    int rec = entitymDao.insert(entitym);
                    log.debug("新增数据返回 {}", rec);
                    result.setResStatus(ResStatus.STATUS_SUCCESS);
                    result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
                } catch (Exception e) {
                    log.error("INSERT TSysParam " + e.getLocalizedMessage());
                } finally {
                    rLock.unlock();
                }
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
                logSaveRequest.setRelatedType("sysparam");
                logSaveRequest.setLogTitle("新增系统参数");
                logSaveRequest.setLogContent("参数ID：" + entitym.getId() + "岗位名称:" + entitym.getParamName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("新增");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

        } catch (Exception e) {
            log.error("新增数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }

        return result;

    }

    /**
     * 修改
     *
     * @param map
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doUpdate(SysParamSaveRequest map, RequestPojo requestPojo) {
        Integer TSysParamId = map.getId();
        log.debug("TSysParamSvcImpl.doUpdate parameter: {}", map);
        Result result = new Result();
        //非空验证
        if (Objects.isNull(map.getId())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        TSysParam entitym = new TSysParam();
        BeanUtils.copyProperties(map, entitym);

        entitym.setUpdateBy(requestPojo.getUserName());
        entitym.setUpdateTime(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));

        try {
            RLock rLock = redissonCommand.getFairLock(String.valueOf(entitym.getId()));
            if (rLock.tryLock()) {
                try {
                    int rec = entitymDao.update(entitym);
                } catch (Exception e) {
                    log.error("UPDATE TSysParam " + e.getLocalizedMessage());
                } finally {
                    rLock.unlock();
                }
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
                logSaveRequest.setRelatedType("sysparam");
                logSaveRequest.setLogTitle("修改参数");
                logSaveRequest.setLogContent("参数ID：" + entitym.getId() + "参数名称:" + entitym.getParamName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("修改");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        } catch (Exception e) {
            log.error("修改数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("修改数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }

        return result;

    }

    /**
     * 删除
     *
     * @param map
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doDelete(DeleteRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("TSysParamSvcImpl.doDelete parameter: {}", map);
        //非空验证
        Integer TSysParamID = map.getId();

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        String TSysParamRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + TSysParamID);
        mapData.put("TSysParamID", String.valueOf(TSysParamID));
        List<TSysParam> entitym = entitymDao.selectList(page, mapData);
        if (entitym == null || entitym.size() == 0) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg("数据不存在");
            return result;
        }

        try {
            int rec = entitymDao.deleteById(Integer.valueOf(TSysParamID));
            if (rec > 0) {
                stringRedisTemplate.delete(RedisKeyConstant.USER_MODIFY_LOCK + ":" + TSysParamID);
            }
            log.debug("删除数据返回 {}", rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(TSysParamRedisId));
                logSaveRequest.setRelatedType("sysparam");
                logSaveRequest.setLogTitle("删除参数");
                logSaveRequest.setLogContent("参数ID：" + entitym.get(0).getId() + "参数名称:" + entitym.get(0).getParamName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("删除");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } catch (Exception e) {
            log.error("删除数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("删除出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }

        return result;

    }

}
